package com.hjli.tool;

import java.io.IOException;
import java.util.Properties;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiNiuTool {

	// 七牛密钥
	private String ACCESS_KEY;
	private String SECRET_KEY;

	// 对应要上传到七牛上 你的那个路径（自己建的文件夹 注意设置公开）
	private String BUCKET_NAME;

	// 配置文件昵称
	private String PROPERTY_NAME = "qiniu.properties";

	// 密钥配置
	private Auth auth;
	// 创建上传对象
	private UploadManager uploadManager;

	public QiNiuTool() throws Exception {
		Properties proper = PropertiesTool.getProperty(PROPERTY_NAME);
				
				
		ACCESS_KEY = proper.getProperty("AK");
		SECRET_KEY = proper.getProperty("SK");
		BUCKET_NAME = proper.getProperty("BN");
		auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		uploadManager = new UploadManager();
	}

	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	public String getUpToken() {

		return auth.uploadToken(BUCKET_NAME);
	}

	/**
	 * fileName ： 上传到七牛云保存的名称 fileLocalPath：原文件路径
	 */
	public boolean upload( String fileLocalPath,String fileName) {
		try {
			// 调用put方法上传
			Response res = uploadManager.put(fileLocalPath, fileName, getUpToken());
			// 打印返回的信息
			System.out.println("body"+res.bodyString());
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				// 响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
		}
		return false;
	}
}
